package sy.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sy.pageModel.DataGrid;
import sy.pageModel.Json;
import sy.pageModel.Product;
import sy.service.ProductServiceI;

@Controller
@RequestMapping("/productController")
public class ProductController {

	private ProductServiceI productService;

	public ProductServiceI getProductService() {
		return productService;
	}

	@Autowired
	public void setProductService(ProductServiceI productService) {
		this.productService = productService;
	}

	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

	@RequestMapping("/datagrid")
	@ResponseBody
	public DataGrid datagrid(Product product) {
		DataGrid d = productService.datagrid(product);
		return d;
	}

	@RequestMapping("/remove")
	@ResponseBody
	public Json remove(Product product) {
		Json j = new Json();
		try {
		    productService.remove(product.getIds());		    
		    j.setSuccess(true);
		    j.setMsg("发送邮件结束！");
	    } catch(Exception e) {
	    	j.setSuccess(false);
	    	j.setMsg(e.getMessage());
	    }
		return j;
	}
	
	@RequestMapping("/frozen")
	@ResponseBody
	public Json frozen(Product product) {
		Json j = new Json();
		try {
		    productService.frozen(product.getIds());		    
		    j.setSuccess(true);
		    j.setMsg("删除结束！");
	    } catch(Exception e) {
	    	j.setSuccess(false);
	    	j.setMsg(e.getMessage());
	    }
		return j;
	}

	@RequestMapping("/add")
	@ResponseBody
	public Json add(Product product) {
		Json j = new Json();
		try {
			Product c = productService.save(product);
			j.setSuccess(true);
			j.setMsg("添加成功！");
			j.setObj(c);
		} catch (Exception e) {
			j.setMsg("添加失败:" + e.getMessage());
		}
		return j;
	}

	@RequestMapping("/edit")
	@ResponseBody
	public Json edit(Product product) {
		Json j = new Json();
		try {
			Product c = productService.edit(product);
			j.setSuccess(true);
			j.setMsg("修改成功！");
			j.setObj(c);
		} catch (Exception e) {
			j.setMsg("修改失败！" + e.getMessage());
		}
		System.out.println(j);
		return j;
	}
}
